package com.jiantong.user.impl.service;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.impl.dao.DeclareStationDao;
import com.jiantong.user.model.DeclareStation;
import com.jiantong.user.service.DeclareStationReadService;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by niufei on 2017/4/11.
 *
 */
@Slf4j
@Service
@RpcProvider
public class DeclareStationReadServiceImpl implements DeclareStationReadService{

    private final DeclareStationDao declareStationDao;

    @Autowired
    public DeclareStationReadServiceImpl(DeclareStationDao declareStationDao) {
        this.declareStationDao = declareStationDao;
    }

    @Override
    public Response<List<DeclareStation>> findByProvinceIdAndCityId(LoginUser loginUser) {
        Integer provinceId = loginUser.getUserProfile().getProvinceId();
        Integer cityId = loginUser.getUserProfile().getCityId();
        Integer regionId = loginUser.getUserProfile().getRegionId();
        Integer streetId = loginUser.getUserProfile().getStreetId();
        try{
            Map<String, Object> criteria = Maps.newHashMap();
            if (provinceId != null && cityId !=null && regionId != null) {
                criteria.put("provinceId", provinceId);
                criteria.put("cityId", cityId);
                criteria.put("regionId",regionId);
            }
            List<DeclareStation> declareStations = declareStationDao.findByProvinceIdAndCityId(criteria);
            if(declareStations == null){
                log.error("declareStations(criteria={}) is not found", criteria);
                return Response.fail("declareStations.not.found");
            }
            return Response.ok(declareStations);
        }catch (Exception e){
            log.error("failed to find declareStations(provinceId={},cityId={}), cause:{}", provinceId,cityId, Throwables.getStackTraceAsString(e));
            return Response.fail("declareStations.find.fail");
        }
    }

    @Override
    public Response<List<DeclareStation>> findByIds(List<Long> ids) {
        try{
            return Response.ok(declareStationDao.findByIds(ids));
        }catch (Exception e){
            log.error("failed to find",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to find");
        }
    }

    @Override
    public Response<DeclareStation> findById(Long declareStationId) {
        try{
            return Response.ok(declareStationDao.findById(declareStationId));
        }catch (Exception e){
            log.error("failed to find",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to find");
        }
    }
}
